#include "fsm_base.h"

#include "BaseDef.h"

struct sc_map_fsm fsm_list;

// 注册action
fsm_err_t Register_Action_Interface(Fsm_Ctrl_Def* obj, uint8_t action_id, uint32_t mask, CallbackFunc action_callback) {
	fsm_err_t res;
	
	if ( NULL == obj || action_callback == NULL ) { // 如果传入为空，则不处理
		return STATUS_EEMPTY;
	}
	if ( action_id == 0 || action_id > 32 ) { // 参数错误，id不能为0
		return STATUS_ERROR;
	}
	
	obj->fsm_status_mask[action_id-1] = mask;
	obj->action[action_id-1] = action_callback;
	
	return res;
}// 注册action

// 删除action
fsm_err_t Deregister_Action_Interface(Fsm_Ctrl_Def* obj, uint8_t action_id) {
	fsm_err_t res;
	if ( NULL == obj ) { // 如果传入为空，则不处理
		return STATUS_EEMPTY;
	}
	
	obj->action[action_id-1] = NULL;
	obj->fsm_status_mask[action_id-1] = 0;
	STATU_RESET(obj->fsm_status, (0x01 << (action_id-1)) );
	STATU_RESET(obj->fsm_action_call, (0x01 << (action_id-1)) );
	
	return res;
} // 删除action

// 执行指定的action
fsm_err_t Active_Action_Interface(Fsm_Ctrl_Def* obj, uint8_t action_id){
	fsm_err_t res;
	if ( NULL == obj ) { // 如果传入为空，则不处理
		return STATUS_EEMPTY;
	}
	// 如果掩码不满足要求，就不执行
	if ( STATU_GET_NOT(obj->fsm_status, obj->fsm_status_mask[action_id-1]) ){
		return STATUS_EOK;
	}
	
	if ( NULL != obj->action[action_id-1] ) {
		return obj->action[action_id-1]();
	}else{
		return STATUS_EEMPTY;
	}
	
	return res;
} // 执行指定的action

// 设置指定的状态。
fsm_err_t Active_Status_Interface(struct __TAG_Fsm_Ctrl_Def* obj, uint8_t action_id, bool run_now) {
	fsm_err_t res;
	if ( NULL == obj ) { // 如果传入为空，则不处理
		return STATUS_EEMPTY;
	}
	
	STATU_SET(obj->fsm_status, (0x01 << ( action_id-1 )) );
	STATU_SET(obj->fsm_action_call, (0x01 << ( action_id-1 )) );
	
	if ( run_now ) {
		obj->Active_Action(obj, action_id);
	}
	
	return res;
}// 设置指定的状态。

// 空闲处理函数
fsm_err_t Idle_action_Interface(struct __TAG_Fsm_Ctrl_Def* obj) {
	fsm_err_t res;
	if ( NULL == obj ) { // 如果传入为空，则不处理
		return STATUS_EEMPTY;
	}
	
	// 如果待执行函数数量不为0
	if ( obj->fsm_action_call != 0 ) {
		for (int index=1; index<=32; index++){
			obj->Active_Action(obj, index);
		}
	}// 如果待执行函数数量不为0
	
	return res;
}

// 初始化函数
fsm_err_t Init_Fsm_Interface(Fsm_Ctrl_Def* obj, char* name) {
	if ( NULL == obj ) { // 如果传入为空，则不处理
		return STATUS_EEMPTY;
	}
	
	strcpy(obj->name, name);
	obj->fsm_status = 0x00;
	for (int index=0; index<32; index++ ){
		obj->fsm_status_mask[index] = 0x00;
	}
	obj->fsm_action_call = 0x00;
	
	for ( int index=0; index<32; index++ ) {
		obj->action[index] = NULL;
	}
	
	obj->Init_Fsm = Init_Fsm_Interface;
	obj->Register_Action = Register_Action_Interface;
	obj->Deregister_Action = Deregister_Action_Interface;
	obj->Active_Action = Active_Action_Interface;
	obj->Active_Status = Active_Status_Interface;
	
	return STATUS_EOK;
} // 初始化函数
